package com.easysoft.framework.action;

import com.easysoft.commons.utils.CheckFile;
import com.easysoft.commons.utils.StringUtils;
import com.easysoft.commons.utils.WebConstants;
import com.easysoft.framework.annotation.logs.SystemControllerLog;
import com.easysoft.framework.announce.model.SysAnnounce;
import com.easysoft.framework.announce.model.SysAnnounceQuery;
import com.easysoft.framework.announce.model.SysAnnounceView;
import com.easysoft.framework.announce.service.AnnounceService;
import com.easysoft.framework.beans.Page;
import com.easysoft.framework.manager.model.SysManager;
import com.easysoft.framework.manager.model.SysManagerView;
import com.easysoft.framework.role.model.SysRoleQuery;
import com.easysoft.framework.role.model.SysRoleView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping(SystemAnnounceAction.BASE_VIEW)
public class SystemAnnounceAction {
    public static final String BASE_VIEW = "/announce";
    private final static Logger logger = LoggerFactory.getLogger(SystemProblemAction.class);

    @Autowired
    @Qualifier("service.AnnounceService")
    private AnnounceService announceService;

    /**
     * 分页查询系统公告列表
     * @param page  分页信息
     * @param query 查询条件
     * @return 系统公告列表
     */
    @RequestMapping(value = "/listAnnounce", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView listAnnounce(Page page, SysAnnounceQuery query) {
        logger.info("Call SystemAnnounceAction.listAnnounce({},{})", page.toString(), query.toString());
        List<SysAnnounceView> list = announceService.selectSysAnnounceByPage(page, query);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/listAnnounce");
        mv.addObject("page", page);
        mv.addObject("query", query);
        mv.addObject("listAnnounce", list);
        return mv;
    }

    @RequestMapping(value = "/editAnnounce", method = RequestMethod.GET)
    public ModelAndView editAnnounce(String action, @RequestParam(required = false) String id) {
        logger.info("Call SystemAnnounceAction.editAnnounce({},{})", action, id);
        ModelAndView mv = new ModelAndView(BASE_VIEW + "/editAnnounce");
        SysAnnounceQuery query = new SysAnnounceQuery();

        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(id)) {
                return null;
            }
            return mv;
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(id)) {
                return null;
            }
            SysAnnounceView entity = announceService.selectSysAnnounceViewByPrimaryKey(id);
            if (entity == null) {
                return null;
            }
            mv.addObject("entity", entity);
            return mv;
        }
        return null;
    }

    @RequestMapping(value = "/saveAnnounce", method = RequestMethod.POST)
    public int saveAnnounce(String action, SysAnnounce announce, @RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpServletRequest request, HttpSession session) {
        logger.info("Call SystemAnnounceAction.saveAnnounce({},{})", action,announce.toString());
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("add")) {
            // 添加
            if (StringUtils.isNotNullAndBlank(announce.getId())) {
                return 0;
            }
            return addAnnounce(announce,multipartFile,request,session);
        }
        if (StringUtils.isNotNullAndBlank(action) && action.toLowerCase().equals("update")) {
            // 修改
            if (StringUtils.isNullOrBlank(announce.getId())) {
                return 0;
            }
            return updateAnnounce(announce,multipartFile,request,session);
        }
        return 0;
    }

    /**
     * 添加系统公告
     * @param announce 公告表单信息
     * @param multipartFile 封面图片
     * @return 1 成功，0 失败
     */
    @SystemControllerLog(description = "添加系统公告")
    public int addAnnounce(SysAnnounce announce, @RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpServletRequest request, HttpSession session) {
        logger.info("Call SystemAnnounceAction.addAnnounce({})", announce.toString());
        if(multipartFile != null && !("").equals(multipartFile)){
            announce.setCoverImg( saveArticlePic(multipartFile,announce.getId(),request));
        }
        announce.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
        return announceService.addSysAnnounce(announce);
    }

    /**
     * 根据主键获取系统公告
     * @param id 主键
     * @return 公告信息
     */
    @RequestMapping(value = "/viewAnnounce", method = RequestMethod.POST)
    public SysAnnounce viewAnnounce(String id) {
        logger.info("Call SystemAnnounceAction.viewAnnounce({})", id);
        return announceService.selectSysAnnounceById(id);
    }

    /**
     * 更新系统公告
     * @param announce 系统公告表单信息
     * @return 1 成功，0 失败
     */
    @SystemControllerLog(description = "更新系统公告")
    public int updateAnnounce(SysAnnounce announce, @RequestParam(value="multipartFile", required=false)MultipartFile multipartFile, HttpServletRequest request, HttpSession session) {
        logger.info("Call SystemAnnounceAction.updateAnnounce({})", announce.toString());
        if(multipartFile != null && !("").equals(multipartFile)){
            announce.setCoverImg( saveArticlePic(multipartFile,announce.getId(),request));
        }
        announce.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
        return announceService.updateSysAnnouce(announce);
    }

    /**
     * 删除系统公告
     * @param id 主键
     * @return 1 成功，0 失败
     */
    @SystemControllerLog(description = "删除系统公告")
    @RequestMapping(value = "/deleteAnnounce",method = RequestMethod.POST)
    public int deleteAnnounce(String id){
        logger.info("Call SystemAnnounceAction.deleteAnnounce({})", id);
        return announceService.deleteSysAnnounce(id);
    }

    /**
     * 更新系统公告状态
     * @param id 主键
     * @param status 状态
     * @return 1 成功，0 失败
     */
    @SystemControllerLog(description = "更改系统公告状态")
    @RequestMapping(value = "/updaterAnnounceStatus", method = RequestMethod.POST)
    public int updaterAnnounceStatus(String id, int status,HttpSession session) {
        logger.info("Call SystemAnnounceAction.updaterProblemStatus({},{})", id, status);
        SysAnnounce temp = announceService.selectSysAnnounceById(id);
        temp.setIsStatis(status);
        temp.setOperator((String) session.getAttribute(WebConstants.SESSION_USER_ID));
        return announceService.updateSysAnnouce(temp);
    }

    /**
     * 保存并且上传列表图片
     * @param multipartFile
     * @param categoryId
     * @param request
     * @return
     */
    public String  saveArticlePic(@ModelAttribute MultipartFile multipartFile, String categoryId, HttpServletRequest request) {
        // 判段是否图片
        InputStream in = null;
        Boolean isPicture = false;
        if (multipartFile != null && !("").equals(multipartFile)) {
            try {
                in = multipartFile.getInputStream();
                isPicture = CheckFile.isPicture(in);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            if (isPicture) {
                String currNum = String.valueOf(System.currentTimeMillis());
                return uploadImg(request, categoryId, multipartFile, currNum);
            }
        }
        return null;
    }

    /**
     * @param request
     * @param type       类型
     * @param sourceFile 上传的列表文件
     * @param currNum    文件名
     * @return 图片访问路径
     */
    public String uploadImg(HttpServletRequest request, String type, MultipartFile sourceFile, String currNum) {
        if (!sourceFile.isEmpty()) {
            // 文件保存目录路径
            String savePath = request.getSession().getServletContext().getRealPath("/") + "/images/list" + type + "/";
            String saveUrl = request.getContextPath() + "/images/list" + type + "/";
            // 目录不存在则创建
            File uploadPath = new File(savePath);
            if (!uploadPath.exists()) {
                uploadPath.mkdirs();
            }
            String fileName = sourceFile.getOriginalFilename();
            String dir = fileName.substring(fileName.indexOf("."), fileName.length());
            fileName = currNum + dir;
            try {
                // 文件保存路径
                String filePath = savePath + fileName;
                // 转存文件
                sourceFile.transferTo(new File(filePath));
                return saveUrl + fileName;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }
}
